package com.rebate.web.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.rebate.util.JSonUtil;
import com.rebate.util.Page;

public class BaseServlet {
	protected Log logger = LogFactory.getLog(this.getClass());
	
	protected void print(HttpServletRequest request, HttpServletResponse response,Page page){
		String result = JSonUtil.toJSonString(page.getResult());
		response.setCharacterEncoding("utf-8");
		try {
			response.getWriter().print("{\"total\":"+page.getTotalCount()+",\"rows\":"+result+"}");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("error",e);
		}
	}
	
	protected void printNoPage(HttpServletResponse response,List list){
		String result = JSonUtil.toJSonString(list);
		response.setCharacterEncoding("utf-8");
		try {
			response.getWriter().print("{\"rows\":"+result+"}");
		} catch (IOException e) {
			logger.error("error",e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 只有整数的数字return true
	 * @param num
	 * @return
	 */
	protected boolean isNumber(String num) {
		return StringUtils.isNotBlank(num) && StringUtils.isNumeric(num);
	}
	
	protected Date parseDate(String date) {
		try {
			return DateUtils.parseDate(date, new String[]{"yyyy-MM-dd"});
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
